<template>
  <div class="role-management">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="角色名称">
            <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="operation-box">
        <el-button type="primary" @click="handleAdd">新增角色</el-button>
      </div>

      <!-- 角色列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" fixed="left" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="permissions" label="权限" min-width="200">
          <template #default="scope">
            <el-tooltip
              v-for="permission in scope.row.permissions" 
              :key="permission.id"
              effect="light"
              placement="right"
              :content="getPermissionDescription(permission.name)"
            >
              <el-tag 
                class="permission-tag"
                type="info"
                effect="plain"
              >
                {{ permission.name }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.isSystem"
            >编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.isSystem"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑角色' : '新增角色'"
      width="600px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        class="edit-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限设置" prop="permissions">
          <el-checkbox-group v-model="editForm.permissions">
            <div class="permission-group">
              <el-checkbox 
                v-for="permission in permissionList" 
                :key="permission.id"
                :label="permission.id"
              >
                <el-tooltip
                  effect="light"
                  placement="right"
                  :content="getPermissionDescription(permission.name)"
                >
                  <span>{{ permission.name }}</span>
                </el-tooltip>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDateTime } from '@/utils/format'
import { 
  getRoleListPage,
  addRole,
  updateRole,
  deleteRole,
  getPermissionList,
  getRoleDeleteVerifyCode
} from '@/api/admin'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 权限树数据
const permissionList = ref([])
const permissionTree = ref(null)

// 编辑表单
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  name: '',
  description: '',
  permissions: []
})

// 表单校验规则
const editRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 权限描述映射
const permissionDescriptions = {
  'UserManagementRelated': '用户管理权限：管理用户账户、信息维护、状态管理等',
  'BookManagementRelated': '图书管理权限：图书信息的录入、修改、删除等',
  'CategoryManagementRelated': '分类管理权限：图书分类的创建、编辑、删除等',
  'BorrowingManagementRelated': '借阅管理权限：借阅申请处理、归还管理、逾期处理等',
  'RecommendationManagementRelated': '推荐管理权限：图书推荐规则配置、推荐内容管理等',
  'SystemSettingsRelated': '系统设置权限：系统参数配置、系统维护、日志查看等',
  'StatisticsAnalysisRelated': '统计分析权限：数据统计、分析报表生成、趋势分析等'
}

// 获取权限描述
const getPermissionDescription = (permissionName) => {
  return permissionDescriptions[permissionName] || '暂无描述'
}

// 初始化
onMounted(() => {
  fetchRoleList()
  fetchPermissionList()
})

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const params = {
      page: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
      name: searchForm.name
    }
    const res = await getRoleListPage(params)
    if (res.code === 0) {
      tableData.value = res.data.results
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const res = await getPermissionList()
    if (res.code === 0) {
      permissionList.value = [
        { id: 1, name: 'UserManagementRelated' },
        { id: 2, name: 'BookManagementRelated' },
        { id: 3, name: 'CategoryManagementRelated' },
        { id: 4, name: 'BorrowingManagementRelated' },
        { id: 5, name: 'RecommendationManagementRelated' },
        { id: 6, name: 'SystemSettingsRelated' },
        { id: 7, name: 'StatisticsAnalysisRelated' }
      ]
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 搜索
const onSubmit = () => {
  currentPage.value = 1
  fetchRoleList()
}

// 重置搜索表单
const resetForm = () => {
  searchForm.name = ''
  currentPage.value = 1
  fetchRoleList()
}

// 新增角色
const handleAdd = () => {
  editForm.id = ''
  editForm.name = ''
  editForm.description = ''
  editForm.permissions = []
  editDialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.description = row.description
  editForm.permissions = row.permissions ? row.permissions.map(p => p.id) : []
  editDialogVisible.value = true
}

// 保存角色
const handleSaveRole = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = {
          ...editForm,
          permissions: editForm.permissions
        }
        
        if (editForm.id) {
          const res = await updateRole(formData)
          if (res.code === 0) {
            ElMessage.success('更新成功')
            editDialogVisible.value = false
            fetchRoleList()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          const res = await addRole(formData)
          if (res.code === 0) {
            ElMessage.success('添加成功')
            editDialogVisible.value = false
            fetchRoleList()
          } else {
            ElMessage.error(res.msg || '添加失败')
          }
        }
      } catch (error) {
        console.error('保存角色失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 重置编辑表单
const resetEditForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 删除角色
const handleDelete = async (row) => {
  try {
    // 第一次确认
    await ElMessageBox.confirm(
      '确认要删除该角色吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 获取验证码
    const verifyRes = await getRoleDeleteVerifyCode(row.id)
    if (verifyRes.code !== 0) {
      ElMessage.error(verifyRes.msg || '获取验证码失败')
      return
    }
    
    ElMessage.success('验证码已发送到您的邮箱')

    // 弹出验证码输入框
    const inputRes = await ElMessageBox.prompt(
      '请输入邮箱收到的6位数字验证码',
      '验证码确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]{6}$/,
        inputErrorMessage: '请输入6位数字验证码'
      }
    )

    if (inputRes.action === 'confirm' && inputRes.value) {
      // 调用删除接口
      const res = await deleteRole(row.id, inputRes.value)
      if (res.code === 0) {
        ElMessage.success(res.message || '删除成功')
        fetchRoleList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作，不做处理
      return
    }
    console.error('删除失败:', error)
    if (error?.message?.includes('验证码')) {
      ElMessage.error('验证码错误')
    } else {
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRoleList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRoleList()
}
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.operation-box {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.edit-form {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.el-tree) {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  padding: 10px;
  border-radius: 4px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-expanded > .el-tree-node__children) {
  padding-left: 20px;
}

.permission-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  width: 100%;
  display: flex;
  align-items: center;
}

:deep(.el-checkbox__label) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style> 